﻿using PelitaProduksi.Controller;
using PelitaProduksi.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PelitaProduksi.View.Panel
{
    public partial class FormRajut : Form
    {
        string _id = null;
        int counter = 1;
        public Main main;
        public int code;
        GroupPegawai group;
        short tipe = 0; // 0 NEW, 1 UPDATE
        List<Barang> listBarang;
        List<Pegawai> listPegawai;

        public FormRajut(Main main, int code)
        {
            InitializeComponent();
            this.main = main;
            this.code = code;
            tipe = 0;
            init(tipe);
        }

        public FormRajut(Main main, int code, string id)
        {
            InitializeComponent();
            this.main = main;
            this.code = code;
            this._id = id;
            if (_id != null) tipe = 1;
            else tipe = 0;
            init(tipe);
        }

        ~FormRajut()
        {
            this.main.LIST_FORMS.Remove(this.code);
            closeGroup();
        }

        private void closeGroup()
        {
            if (group != null)
            {
                group.Close();
                group = null;
            }
        }

        private void init(short tipe)
        {
            listPegawai = Pegawai.listAllPegawai(true);
            foreach (Pegawai p in listPegawai)
            {
                pegawai1.Items.Add(p.Nama);
                pegawai2.Items.Add(p.Nama);
                pegawai3.Items.Add(p.Nama);
            }

            listBarang = Barang.listAllBarang(true);
            
            if (tipe == 1)
            {
                Rajut r = Rajut.getRajut(_id);
                // Update 
                // --  Show Update box
                txtUpdate1.Text = r.UpdateDate;
                txtUpdate2.Text = r.UpdateTime;
                txtUpdate3.Text = r.User;
                // -- Update other columns
                // -- Update Detail Rajut
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            closeGroup();
            // Search the group from database
            Pegawai p1, p2, p3;
            p1 = null;
            p2 = null;
            p3 = null;
            group = new GroupPegawai(pegawai1, pegawai2, pegawai3, p1, p2, p3);
            group.Visible = true;
            group.Activate();
            group.BringToFront();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // Validate if something still empty
            if (pegawai1.SelectedIndex < 0)
            {
                MessageBox.Show("Minimal ada 1 Pegawai yang harus diisi");
                return;
            }
            if (detail.Rows.Count <= 0)
            {
                MessageBox.Show("Minimal ada 1 Laporan Rajut yang harus diisi");
                return;
            }
            else if (detail.Rows.Count == 1)
            {
                if ((detail.Rows[0].Cells["gridKode"].Value == null)
                || (detail.Rows[0].Cells["gridNolap"].Value == null))
                    MessageBox.Show("Minimal ada 1 Laporan Rajut yang harus diisi");
                    return;                
            }
            // Insert
            Rajut rajut = new Rajut();
            int total = 0;
            for (int i = 0; i < detail.Rows.Count; i++)
            {
                int jumlahRajut = 0;
                object obj = detail.Rows[i].Cells["gridRajut"].Value;
                if (obj != null)
                {
                    string strRajut = obj.ToString();
                    if (!string.IsNullOrEmpty(strRajut))
                        jumlahRajut = Int32.Parse(strRajut);
                }
                if (jumlahRajut == 0) continue;
                // Invalid input, ignore
                if (detail.Rows[i].Cells["gridKode"].Value == null && jumlahRajut>0)
                {
                    MessageBox.Show("Kode Barang tidak boleh kosong");
                    return;
                }
                if (detail.Rows[i].Cells["gridNolap"].Value == null && jumlahRajut > 0)
                {
                    MessageBox.Show("Nomor laporan tidak boleh kosong");
                    return;
                }
                // insert Data
                RajutDetail det = new RajutDetail();
                // Problem: Can't get Object within the combobox inside the cell
                string value = detail.Rows[i].Cells["gridKode"].Value.ToString();
                string kode = null;
                foreach (Barang b in listBarang)
                {
                    if (b.Nama.ToUpper().Equals(value.ToUpper()))
                    {
                        kode = b.Kode;
                    }
                }
                if (kode == null)
                {
                    MessageBox.Show(string.Format("Barang {0} tidak ada di dalam daftar", value));
                    return;
                }
                string year = DateTime.Now.Year + "";
                year = year.Substring(2, 2);
                det.KodeBarang = kode;
                det.Nolap = year+detail.Rows[i].Cells["gridNolap"].Value.ToString();
                det.Rajut = jumlahRajut;
                rajut.List.Add(det);
                total += det.Rajut;
            }
            // Fill rajut data
            rajut.Shift = Int32.Parse(txtShift.Text);
            rajut.Tanggal = DateController.Instance.getDate(tanggal.Value);
            string kp1, kp2, kp3;
            kp1 = null; kp2 = null; kp3 = null;
            foreach (Pegawai p in listPegawai)
            {
                if (kp1 != null && kp2 != null && kp3 != null) break;
                if (p.Nama.Equals(pegawai1.SelectedItem.ToString()))
                    kp1 = p.Kode;
                if (pegawai2.SelectedIndex != -1 && p.Nama.Equals(pegawai2.SelectedItem.ToString()))
                    kp2 = p.Kode;
                if (pegawai3.SelectedIndex != -1 && p.Nama.Equals(pegawai3.SelectedItem.ToString()))
                    kp3 = p.Kode;
            }
            rajut.Nama1 = kp1;
            rajut.Nama2 = kp2;
            rajut.Nama3 = kp3;
            rajut.Hadir1 = checkBox1.Checked;
            rajut.Hadir2 = checkBox2.Checked;
            rajut.Hadir3 = checkBox3.Checked;
            rajut.Keterangan = txtKeterangan.Text;
            rajut.UpdateDate = DateController.Instance.getDate(DateTime.Now);
            rajut.UpdateTime = DateController.Instance.getTime(DateTime.Now);
            rajut.User = main.USER;
            rajut.Total = total;
            // Insert or Update
            if (tipe == 0)
            {
                // Generate new ID
                rajut.NoReg = rajut.getID("rajut");
                // INSERT
                rajut.insert();
            }
            else if (tipe == 1) rajut.edit(_id);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void detail_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (detail.CurrentRow.Cells["No"].Value == null)
                detail.CurrentRow.Cells["No"].Value = counter++;
            if (detail.CurrentRow.Cells["gridRajut"].Value == null)
                detail.CurrentRow.Cells["gridRajut"].Value = 0;
        }

        private void detail_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            // Check for error on input (alphabet)
            if (detail != null && detail.CurrentRow != null &&
                detail.CurrentRow.Cells != null && detail.CurrentRow.Cells.Count > 0 &&
                detail.CurrentRow.Cells["gridRajut"].Value != null)
            {
                int value = 0;
                try
                {
                    value = Int32.Parse(detail.CurrentRow.Cells["gridRajut"].Value.ToString());
                }
                catch(Exception) {}
                detail.CurrentRow.Cells["gridRajut"].Value = value;
            }
        }

        private void txtShift_Leave(object sender, EventArgs e)
        {
            int i = 0;
            try
            {
                i = Int32.Parse(txtShift.Text);
            }
            catch (Exception)
            {
                i = -1;
            }
            if (i < 1 || i > 3)
            {
                txtShift.Text = "1";
                MessageBox.Show("Shift hanya boleh 1-3");
                txtShift.Focus();
            }
        }

        private void detail_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            // Do nothing to prevent unneccessary popup message
        }

        private void detail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            int column = detail.CurrentCell.ColumnIndex;

            if (column==1)
            {
                TextBox tb = e.Control as TextBox;

                if (tb != null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    tb.AutoCompleteCustomSource = AutoCompleteLoad();
                    tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
                }
            }
        }

        public AutoCompleteStringCollection AutoCompleteLoad()
        {
            AutoCompleteStringCollection str = new AutoCompleteStringCollection();
            DataGridViewTextBoxColumn c = (DataGridViewTextBoxColumn)detail.Columns["gridKode"];
            foreach (Barang b in listBarang)
            {
                str.Add(b.Nama);
            }
            return str;
        }
    }
}
